<template>
  <div class="p-2">
    <transition :enter-active-class="proxy?.animate.searchAnimate.enter" :leave-active-class="proxy?.animate.searchAnimate.leave">
      <div v-show="showSearch" class="mb-[10px]">
        <el-card shadow="never">
          <el-form ref="queryFormRef" :model="allocateQueryParams" :inline="true" :rules="dateRules">
            <el-form-item label="年-月" prop="date">
              <el-date-picker clearable v-model="allocateQueryParams.date" type="month" value-format="YYYY-MM" placeholder="请选择日期" style="width: 170px"/>
            </el-form-item>
            <el-form-item label="院区" prop="yardCode">
              <el-select v-model="allocateQueryParams.yardCode" placeholder="全部" clearable style="width: 170px">
                <el-option v-for="dict in yard_type" :key="dict.value" :label="dict.label" :value="dict.value" />
              </el-select>
            </el-form-item>
            <el-form-item label="预算部门" prop="budgetDeptCode">
              <el-select v-model="allocateQueryParams.budgetDeptCode" placeholder="请选择预算部门" filterable clearable style="width: 170px">
                <el-option v-for="dict in deptList" :key="dict.deptCode" :label="dict.deptName" :value="dict.deptCode" />
              </el-select>
            </el-form-item>
            <el-form-item label="预算科目名称" prop="subjectName" label-width="170px">
              <el-input v-model="allocateQueryParams.subjectName" placeholder="请输入" clearable @keyup.enter="handleQuery" style="width: 170px" />
            </el-form-item>
            <el-form-item label="会计科目名称" prop="accountSubjectName" label-width="170px">
              <el-input v-model="allocateQueryParams.accountSubjectName" placeholder="请输入" @keyup.enter="handleQuery" style="width: 170px" />
            </el-form-item>

            <el-form-item label="分配状态" prop="state">
              <el-select v-model="allocateQueryParams.state" placeholder="全部" clearable style="width: 170px">
                <el-option v-for="dict in allot_state" :key="dict.value" :label="dict.label" :value="dict.value" />
              </el-select>
            </el-form-item>
            <el-form-item label="来源" prop="source">
              <el-select v-model="allocateQueryParams.source" placeholder="全部" clearable style="width: 170px">
                <el-option v-for="dict in data_source" :key="dict.value" :label="dict.label" :value="dict.value" />
              </el-select>
            </el-form-item>
            <el-form-item >
              <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
              <el-button icon="Refresh" @click="resetQuery">重置</el-button>
            </el-form-item>
          </el-form>
        </el-card>
      </div>
    </transition>

    <el-card shadow="never">
      <template #header>
        <div style="display: flex; justify-content: space-between; align-items: center; padding: 0 16px;">
          <el-row :gutter="10" class="mb8">
            <el-col :span="1.5">
              <el-button type="primary" plain icon="Plus" @click="handleAdd" v-hasPermi="['collect:dataExpenseFinal:add']">新增</el-button>
            </el-col>
            <el-col :span="1.5">
              <el-button type="warning" plain icon="Download" @click="handleExport" v-hasPermi="['collect:dataExpenseFinal:export']">导出</el-button>
            </el-col>
          </el-row>
          <span style="color: orangered; margin: 5px 0 0 20px">【总计】：{{ propertyTotal }} 元</span>
        </div>
      </template>

      <el-table border v-loading="loading" :data="expenseList" class="enhanced-table">
        <el-table-column label="主键id" align="center" prop="id" v-if="false" />
        <!--        <el-table-column label="编号" align="center" prop="num" width="80" />-->
        <el-table-column label="预算科目编码" align="center" prop="subjectCode" width="150" />
        <el-table-column label="预算科目名称" align="center" prop="subjectName" width="180" show-overflow-tooltip />
        <el-table-column label="预算部门编码" align="center" prop="budgetDeptCode" width="120" />
        <el-table-column label="预算部门名称" align="center" prop="budgetDeptName" width="150" show-overflow-tooltip />
        <el-table-column label="会计科目编码" align="center" prop="accountSubjectCode" width="180" show-overflow-tooltip />
        <el-table-column label="会计科目名称" align="center" prop="accountSubjectName" width="180" show-overflow-tooltip />
        <el-table-column label="日期" align="center" prop="date" width="150">
          <template #default="scope">
            <span>{{ parseTime(scope.row.date, '{y}-{m}-{d}') }}</span>
          </template>
        </el-table-column>
        <el-table-column label="凭证号" align="center" prop="voucherNum" width="150" />

        <el-table-column label="HIS部门编码" align="center" prop="deptCode" width="120" />
        <el-table-column label="HIS部门名称" align="center" prop="deptName" width="150" show-overflow-tooltip />
        <el-table-column label="摘要" align="center" prop="summary" show-overflow-tooltip min-width="200" />
        <el-table-column label="金额" align="center" prop="md" width="150" show-overflow-tooltip />
        <el-table-column label="院区" align="center" prop="yardName" width="100" />
        <el-table-column label="来源" align="center" prop="source" width="100" >
          <template #default="scope">
            <dict-tag :options="data_source" :value="scope.row.source" />
          </template>
        </el-table-column>
        <el-table-column label="分配状态" align="center" prop="state" fixed="right" width="100">
          <template #default="scope">
            <dict-tag :options="allot_state" :value="scope.row.state" />
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width" fixed="right" min-width="150">
          <template #default="scope">
            <el-tooltip content="修改" placement="top" v-if="scope.row.source === 'SYSTEM'">
              <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['collect:dataExpenseFinal:edit']"></el-button>
            </el-tooltip>
            <el-tooltip content="删除" placement="top" v-if="scope.row.source === 'SYSTEM'">
              <el-button
                link
                type="primary"
                icon="Delete"
                @click="handleDelete(scope.row)"
                v-hasPermi="['collect:dataExpenseFinal:remove']"
              ></el-button>
            </el-tooltip>
            <el-tooltip content="分配" placement="top" v-if="scope.row.state === '0'">
              <el-button
                link
                type="success"
                icon="Right"
                @click="handleAllocation(scope.row, 0)"
                v-hasPermi="['collect:dataExpenseFinal:allot']"
                plain
              >
              </el-button>
            </el-tooltip>
            <el-tooltip content="撤销" placement="top" v-else-if="scope.row.state === '1'">
              <el-button link type="danger" icon="Back" @click="handleAllocation(scope.row, 1)" v-hasPermi="['collect:dataExpenseFinal:back']" plain>
              </el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>

      <pagination v-show="total > 0" :total="total" v-model:page="allocateQueryParams.pageNum" v-model:limit="allocateQueryParams.pageSize" @pagination="getList" />
    </el-card>
    <!-- 添加或修改费用类数据对话框 -->
    <el-dialog :title="dialog.title" v-model="dialog.visible" style="width: 500px" append-to-body>
      <el-form ref="expenseFinalFormRef" :model="form" :rules="rules" label-width="120px">
        <el-form-item label="编号" prop="num" v-if="false">
          <el-input v-model="form.num" placeholder="请输入编号" />
        </el-form-item>
        <el-form-item label="院区" prop="yardCode">
          <el-select v-model="form.yard" placeholder="请选择院区" clearable>
            <el-option v-for="dict in yard_type" :key="dict.value" :label="dict.label" :value="dict.value" />
          </el-select>
        </el-form-item>
        <el-form-item label="预算科目" prop="subjectCode">
          <el-select v-model="form.subjectCode" placeholder="请选择预算科目" filterable clearable>
            <el-option v-for="dict in subjectList" :key="dict.subjectCode" :label="dict.subjectName" :value="dict.subjectCode" />
          </el-select>
        </el-form-item>
        <el-form-item label="会计科目" prop="accountSubjectCode">
          <el-select v-model="form.accountSubjectCode" placeholder="请选择会计科目" filterable clearable>
            <el-option v-for="dict in subjectList" :key="dict.subjectCode" :label="dict.subjectName" :value="dict.subjectCode" />
          </el-select>
        </el-form-item>
        <el-form-item label="预算部门" prop="budgetDeptCode">
          <el-select v-model="form.budgetDeptCode" placeholder="请选择预算部门" filterable clearable>
            <el-option v-for="dict in deptList" :key="dict.deptCode" :label="dict.deptName" :value="dict.deptCode" />
          </el-select>
        </el-form-item>
        <el-form-item label="日期" prop="date">
          <el-date-picker
            clearable
            v-model="form.date"
            type="date"
            placeholder="请选择时间"
            format="YYYY-MM-DD"
            value-format="YYYY-MM-DD"
            @change="dateChange"
          />
        </el-form-item>
        <el-form-item label="会计期间" prop="period">
          <el-input v-model="form.period" placeholder="请输入时段：例如2024-09" />
        </el-form-item>
        <el-form-item label="凭证号" prop="voucherNum" v-if="false">
          <el-input v-model="form.voucherNum" placeholder="请输入凭证号" />
        </el-form-item>
        <el-form-item label="部门编码" prop="deptCode" v-if="false">
          <el-input v-model="form.deptCode" placeholder="请输入部门编码" />
        </el-form-item>
        <el-form-item label="部门名称" prop="deptName" v-if="false">
          <el-input v-model="form.deptName" placeholder="请输入部门名称" />
        </el-form-item>
        <el-form-item label="借方金额" prop="md">
          <el-input v-model="form.md" placeholder="请输入金额：md" />
        </el-form-item>
        <el-form-item label="摘要" prop="summary">
          <el-input v-model="form.summary" type="textarea" placeholder="请输入内容" />
        </el-form-item>
        <el-form-item label="贷方金额" prop="mc" v-if="false">
          <el-input v-model="form.mc" placeholder="请输入金额：mc" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button :loading="buttonLoading" type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
    <!-- 分配（费用类数据）对话框 -->
    <el-dialog :title="dialog.title" v-model="allocateDialog.visible" style="width: 500px" append-to-body>
      <el-form ref="allocationFormRef" :model="allocateForm" label-width="80px">
        <el-form-item label="预算科目 ">
          <el-tree-select
            v-model="allocateForm.subjectCode"
            :data="subjectList"
            :props="{ value: 'subjectCode', label: 'subjectName', children: 'children', disabled: 'disabled' }"
            value-key="subjectCode"
            placeholder="请选择预算科目"
            check-strictly
            @node-click="handleNodeClick"
            filterable
          />
        </el-form-item>
        <el-form-item label="预算部门 ">
          <el-tree-select
            v-model="allocateForm.budgetDeptCode"
            :data="deptList"
            :props="{ value: 'deptId', label: 'deptName', children: 'children', disabled: 'disabled' }"
            value-key="deptCode"
            placeholder="请选择预算部门"
            check-strictly
            @node-click="handleBudgetDeptClick"
            filterable
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button :loading="buttonLoading" type="primary" @click="allocateSubmitForm">确 定</el-button>
          <el-button @click="allocateCancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="expense" lang="ts">
import { AllocationForm, AllocationQuery, AllocationVO } from '@/api/collect/allocation/types';
import { parseTime } from '@/utils/ruoyi';
import {
  allocation,
  listAllocationFinal,
  withdraw,
  totalProperty,
  getExpenseFinal,
  addExpenseFinal,
  updateExpenseFinal,
  delExpenseFinal
} from '@/api/collect/execute/expense';
import { ExpenseFinalVO, ExpenseFinalForm, ExpenseFinalQuery } from '@/api/collect/execute/expense/types';
import useDate from '@/hooks/useDate';
import { BudgetSubjectQuery, BudgetSubjectVO } from '@/api/budget/budgetSubject/types';

import { listBudgetSubject } from '@/api/budget/budgetSubject';
import { ref } from 'vue';
import { DeptVO } from '@/api/budget/budgetDept/types';
import { getDeptList } from '@/api/budget/budgetDept';

const { proxy } = getCurrentInstance() as ComponentInternalInstance;

const { allot_state, yard_type,data_source } = toRefs<any>(proxy?.useDict('allot_state', 'yard_type','data_source'));
const expenseList = ref<AllocationVO[]>([]);
const propertyTotal = ref(0);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref<Array<string | number>>([]);
const total = ref(0);

const queryFormRef = ref<ElFormInstance>();
const allocationFormRef = ref();
const expenseFinalFormRef = ref<ElFormInstance>();

const allocateQueryParams = ref<AllocationQuery>({
  pageNum: 1,
  pageSize: 10,
  date: useDate.getPreviousMonth(),
  yardCode: undefined,
  budgetDeptCode: undefined,
  subjectName: undefined,
  accountSubjectName: undefined,
  state: undefined,
  type: 1, //默认
  source:undefined
});

/*预算部门列表*/
const getBudgetDeptList = () => {
  getDeptList(allocateQueryParams.value.type).then((res) => {
    deptList.value = res.data;
  });
};

/** 查询数据分配（费用类数据）列表 */
const getList = async () => {
  loading.value = true;
  const res = await listAllocationFinal(allocateQueryParams.value);
  expenseList.value = res.data.records;
  total.value = res.data.total;
  loading.value = false;
};

/** 查询费用类数据总计 */
const getTotal = async () => {
  const res = await totalProperty(allocateQueryParams.value);
  propertyTotal.value = res.data;
};

/** 搜索按钮操作 */
const handleQuery = () => {
  queryFormRef.value.validate((valid) => {
    if (valid) {
      allocateQueryParams.value.pageNum = 1;
      getList();
      getTotal();
    } else {
      return;
    }
  });
};

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value?.resetFields();
  handleQuery();
};

const allocateDialog = reactive<DialogOption>({
  visible: false,
  title: ''
});
const dialog = reactive<DialogOption>({
  visible: false,
  title: ''
});
const initAllocateFormData: AllocationForm = {
  id: undefined,
  subjectCode: undefined,
  budgetDeptCode: undefined,
  isEnd: false
};
const allocateForm = ref<AllocationForm>({ ...initAllocateFormData });

const dateRules = ref({
  date: [{ required: true, message: '请选择年月', trigger: 'change' }]
});

const buttonLoading = ref(false);
const subjectList = ref<BudgetSubjectVO[]>([]);
const deptList = ref<DeptVO[]>([]);

/** 分配表单重置 */
const allocateReset = () => {
  allocateForm.value.id = undefined;
  allocateForm.value.isEnd = undefined;
  allocateForm.value.subjectCode = undefined;
  allocateForm.value.budgetDeptCode = undefined;
};

const initFormData: ExpenseFinalForm = {
  id: undefined,
  num: undefined,
  subjectCode: undefined,
  subjectName: undefined,
  accountSubjectCode: undefined,
  accountSubjectName: undefined,
  date: undefined,
  period: undefined,
  voucherNum: undefined,
  deptCode: undefined,
  deptName: undefined,
  summary: undefined,
  md: undefined,
  mc: undefined,
  yardName: undefined,
  state: undefined,
  yard: undefined,
  budgetDeptCode: undefined,
  budgetDeptName: undefined,
  source: 'SYSTEM'
};
const data = reactive<PageData<ExpenseFinalForm, ExpenseFinalQuery>>({
  form: { ...initFormData },
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    num: undefined,
    subjectCode: undefined,
    subjectName: undefined,
    accountSubjectCode: undefined,
    accountSubjectName: undefined,
    date: undefined,
    period: undefined,
    voucherNum: undefined,
    deptCode: undefined,
    deptName: undefined,
    summary: undefined,
    md: undefined,
    mc: undefined,
    yardName: undefined,
    state: undefined,
    yard: undefined,
    budgetDeptCode: undefined,
    budgetDeptName: undefined,
    source: undefined,
    params: {}
  },
  rules: {
    subjectCode: [{ required: true, message: '请选择预算科目', trigger: 'blur' }],
    accountSubjectCode: [{ required: true, message: '请选择会计科目', trigger: 'blur' }],
    date: [{ required: true, message: '日期不能为空', trigger: 'blur' }],
    period: [{ required: true, message: '会计期间不能为空', trigger: 'blur' }],
    md: [{ required: true, message: '金额不能为空', trigger: 'blur' }],
    yard: [{ required: true, message: '院区不能为空', trigger: 'blur' }],
    budgetDeptCode: [{ required: true, message: '预算部门不能为空', trigger: 'blur' }]
  }
});

const { queryParams, form, rules } = toRefs(data);

/** 取消按钮 */
const allocateCancel = () => {
  allocateReset();
  allocateDialog.visible = false;
};

/** 取消按钮 */
const cancel = () => {
  reset();
  dialog.visible = false;
};

/** 表单重置 */
const reset = () => {
  form.value = { ...initFormData };
  expenseFinalFormRef.value?.resetFields();
};
/** 分配/撤销按钮操作 */
const handleAllocation = async (row: AllocationVO, type: number) => {
  buttonLoading.value = false;
  allocateReset();
  if (type === 0) {
    //分配
    initAllocateFormData.id = row.id;
    allocateDialog.visible = true;
    allocateDialog.title = '分配预算科目&部门';
    await getTreeSelect();
  } else if (type === 1) {
    //撤销
    proxy.$modal.confirm('是否确认撤销分配?').then(() => {
      withdraw(row.id).then(() => {
        proxy.$modal.msgSuccess('操作成功');
        getList();
      });
    });
  }
};
/** 科目树形下拉框*/
const listParams = ref<BudgetSubjectQuery>({
  state: '0', //正常
  label: 2
});
//树形结构列表数据
const getTreeSelect = async () => {
  subjectList.value = [];
  const res = await listBudgetSubject(listParams.value);
  subjectList.value = res.data;
};

const handleNodeClick = (data: BudgetSubjectVO) => {
  console.log(data);
  initAllocateFormData.subjectCode = data.subjectCode;
};

const handleBudgetDeptClick = (data: DeptVO) => {
  console.log(data);
  initAllocateFormData.budgetDeptCode = data.deptCode;
};

/** 提交按钮 */
const allocateSubmitForm = async () => {
  if (!allocateForm.value.subjectCode || !allocateForm.value.budgetDeptCode) {
    proxy.$modal.msgError('预算科目/预算部门不能为空');
    return;
  }
  buttonLoading.value = true;
  try {
    await allocation(initAllocateFormData);
    proxy.$modal.msgSuccess('分配成功');
    allocateDialog.visible = false;
    await getList();
  } catch (error) {
    console.error('分配失败:', error);
  } finally {
    buttonLoading.value = false;
  }
};

/** 导出按钮操作 */
const handleExport = () => {
  proxy?.download(
    'collect/dataExpenseFinal/export',
    {
      ...allocateQueryParams.value
    },
    `费用类数据_${new Date().getTime()}.xlsx`
  );
};

/** 新增按钮操作 */
const handleAdd = () => {
  reset();
  dialog.visible = true;
  dialog.title = '添加费用类数据';
};

/** 修改按钮操作 */
const handleUpdate = async (row?: ExpenseFinalVO) => {
  reset();
  const _id = row?.id || ids.value[0];
  const res = await getExpenseFinal(_id);
  Object.assign(form.value, res.data);
  dialog.visible = true;
  dialog.title = '修改费用类数据';
};

/** 提交按钮 */
const submitForm = () => {
  expenseFinalFormRef.value?.validate(async (valid: boolean) => {
    if (valid) {
      buttonLoading.value = true;

      // 在提交前对名称字段进行赋值
      // 院区名称赋值
      if (form.value.yard) {
        const yardItem = yard_type.value.find((item: any) => item.value === form.value.yard);
        form.value.yardName = yardItem ? yardItem.label : '';
      }

      // 预算科目名称赋值
      if (form.value.subjectCode) {
        const subjectItem = subjectList.value.find((item: any) => item.subjectCode === form.value.subjectCode);
        form.value.subjectName = subjectItem ? subjectItem.subjectName.split('-')[1] : '';
      }

      // 会计科目名称赋值
      if (form.value.accountSubjectCode) {
        const accountSubjectItem = subjectList.value.find((item: any) => item.subjectCode === form.value.accountSubjectCode);
        form.value.accountSubjectName = accountSubjectItem ? accountSubjectItem.subjectName.split('-')[1] : '';
      }

      // 预算部门名称赋值
      if (form.value.budgetDeptCode) {
        const deptItem = deptList.value.find((item: any) => item.deptCode === form.value.budgetDeptCode);
        form.value.budgetDeptName = deptItem ? deptItem.deptName : '';
      }
      //默认赋值
      // form.value.source ='SYSTEM';
      try {
        if (form.value.id) {
          await updateExpenseFinal(form.value);
        } else {
          await addExpenseFinal(form.value);
        }
        proxy?.$modal.msgSuccess('操作成功');
        dialog.visible = false;
        await getList();
      } finally {
        buttonLoading.value = false;
      }
    }
  });
};
/** 删除按钮操作 */
const handleDelete = async (row?: ExpenseFinalVO) => {
  const _ids = row?.id || ids.value;
  await proxy?.$modal.confirm('是否确认删除费用类数据编号为"' + _ids + '"的数据项？').finally(() => (loading.value = false));
  await delExpenseFinal(_ids);
  proxy?.$modal.msgSuccess('删除成功');
  await getList();
};

const dateChange = () => {
  if (form.value.date) {
    // 确保 date 是 Date 对象
    const date = new Date(form.value.date);
    const year = date.getFullYear();
    const month = String(date.getMonth() + 1).padStart(2, '0'); // 月份从0开始，需要+1
    form.value.period = `${year}-${month}`;
  } else {
    form.value.period = ''; // 如果日期被清空，也清空period
  }
};

onMounted(() => {
  getTreeSelect();
  getBudgetDeptList();
  getList();
});
</script>
<style lang="scss" scoped></style>
